// 数据模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Joi = require('joi'); //数据校验插件
Joi.objectId = require('joi-objectid')(Joi); //数据校验插件

const userSchema = new Schema({
	name: {
		type: String,
		required: true
	},
	password: {
		type: String,
		required: true
	},
	// 角色
	role: { type: mongoose.Schema.Types.ObjectId, ref: 'Role' },
	dept: { type: mongoose.Schema.Types.ObjectId, ref: 'Dept' },
	data: {
		type: Date,
		default: () => new Date(Date.now() + 8 * 3600 * 1000)
	},
	// 封面/头像
	avatar_url: {
		type: String
	},
	// 性别
	gender: {
		type: String,
		enum: ['male', 'female'],
		default: 'male',
		required: true
	},
	// 一句话介绍
	headline: {
		type: String
	},
	// 居住地
	locations: {
		type: String
	},
	// 行业
	business: {
		type: String
	},
});

function userValidator(data) {
	console.log('data', data);
	const schema = Joi.object({
		name: Joi.string().trim().min(2).max(30).required().messages({
			'any.required': '缺少必选参数 name',
			'string.name': 'name 格式错误',
			'string.min': 'name最少为2个字符',
			'string.max': 'name最多为16个字符'
		}),
		password: Joi.string()
			.min(5)
			.max(16)
			.pattern(/^[a-zA-Z0-9]{4,16}$/)
			.required()
			.messages({
				'any.required': '密码不能为空',
				'string.min': '密码不能为空',
				'string.min': 'name最少为5个字符',
				'string.max': 'name最多为16个字符'
			}),
		_id: Joi.objectId()
	});
	return schema.validate(data);
}
const User = mongoose.model('users', userSchema);
module.exports = {
	User,
	userValidator
};
